package com.blog.base.interceptor;

import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

public class SpringMVCInterceptor implements HandlerInterceptor  {

	/*springMVC拦截之前*/
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//初始化分页参数
		if(request.getParameter("pageSize")!=null &&request.getParameter("pageNum")!=null)
			PageHelper.startPage(Integer.parseInt(request.getParameter("pageNum")),Integer.parseInt(request.getParameter("pageSize")));
		return true;
	}

	/*springMVC拦截之后*/
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//返回页面之前对modelAndView中的参数过滤 如果发现key为‘List’切分页参数不为空，在此做分页集中处理
		if(request.getParameter("pageSize")!=null && request.getParameter("pageNum")!=null)
		{
			Iterator<Entry<String, Object>> it = modelAndView.getModelMap().entrySet().iterator();
			while(it.hasNext())
			{
				Entry<String, Object> entry = (Entry<String, Object>) it.next(); 
				if(entry.getKey().indexOf("List")!=-1)
				{
					PageInfo page = new PageInfo((List) entry.getValue()); 
					request.setAttribute("page", page);
				}
			}
		}
	}

	/*springMVC返回页面之后*/
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}
	

	
}